package apptoko.com.fragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import apptoko.com.AppManageActivity;
import apptoko.com.ItemBrokerActivity;
import apptoko.com.SettingsActivity;
import apptoko.com.adapter.NotificationHelper;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.AllBannerSuccessEvent;
import apptoko.com.event.Event.HasUpdateContentEvent;
import apptoko.com.model.AppStoreVnApplicationInfo;
import apptoko.com.model.BannerItem;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;

import com.androidquery.AQuery;
import apptoko.com.R;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class HomeMetroFragment extends BaseFragment implements OnClickListener {
	
	private static final String KEY_CONTENT = "Fragment:Metro";
	private String mContent = "";
	public static final String PAGE = "page";
	public static final String KEY_DATE = "_date";
	public static final String KEY_IS_SHOWN = "_shown";
	public static final String BACK_TO_EXIT = "_back_once";
	private Map<String, BannerItem> bannerList;
	private String page;
	private static final int APP_ACTIVITY_REQUEST_CODE = 203;
	private EventBus eventBus;
	private AQuery aquery;
	private BackgroundTasks bgTask;
	private String countryCode;

	public static HomeMetroFragment newInstance(String content) {
		HomeMetroFragment fragment = new HomeMetroFragment();
		fragment.mContent = content;
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mParent = inflater.inflate(R.layout.featured_layout, null);
		aquery = new AQuery(mParent);
		return mParent;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, mContent);
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		countryCode = Utils.getStaticCountryCode(mContext);
		bgTask = new BackgroundTasks(mContext);
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		page = getArguments().getString(PAGE);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
		String todayStr = sdf.format(date);
		String savedDate = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getString(KEY_DATE, "");
		if(savedDate.equals("")){
			getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(KEY_DATE, todayStr).commit();
		} else {
			try {
				Date today = sdf.parse(todayStr);
				Date saved = sdf.parse(savedDate);
				if(today.after(saved)){
					getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putInt(KEY_IS_SHOWN, 0).commit();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void initActions() {
		String store = getArguments().getString(PAGE);
		if(page.equals("games")){
			store = "android";
			page = "game";
		} else if(page.equalsIgnoreCase("apps")){
			store = "android";
			page = "app";
		} else if(page.equals("books")){
			store = "ebook_android";
			page = "home";
		} else if(page.equals("comics")){
			store = "comic_android";
			page = "home";
		} else if(page.equalsIgnoreCase("movies")){
			store = "film_android";
			page = "home";
		} else {
			store = page;
		}
		String accessToken = Utils.getStaticAccessToken(getActivity());
		//EasyTracker.getTracker().sendView(store + "/Banner");
		bgTask.getAllBanners(accessToken, store, page, "feature");
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == 1 && resultCode == Activity.RESULT_OK){

		}
	}
	
	private void onClickBanner(String key){
		String store = Utils.getStaticCurrentStore(getActivity());
		EasyTracker.getTracker().sendEvent(Constants.EVENT, store + "/BannerClick", key + " - " + bannerList.get(key).getName(), Long.valueOf(10));
		String slug = bannerList.get(key).getSlug();
		if(slug.equalsIgnoreCase(Constants.APPSTORE_BANNER)){
			//switchStore("android");
		} else if(slug.equalsIgnoreCase(Constants.GAMESTORE_BANNER)){
			//switchStore("game");
		} else if(slug.equalsIgnoreCase(Constants.BANNER_SPIN_SLUG)){
			//startSpinGame();
		} else if(slug.equalsIgnoreCase(Constants.BANNER_FREE_TYM_SLUG)){
			//getFreeTymMetaps();
		} else {
			if(bannerList.get(key).getType().equalsIgnoreCase("app")){
				bgTask.clickBanner(bannerList.get(key).getUrl());
				if(slug.startsWith("market")||slug.startsWith("http")){
					try {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(slug)));
					} catch (android.content.ActivityNotFoundException anfe) {
					}
				} else{
					Intent i = new Intent(getActivity(), ItemBrokerActivity.class);
					i.putExtra(Constants.SLUG, slug);
					i.putExtra(Constants.PREVIOUS_SCREEN, store + "/Banner");
					i.putExtra(Constants.KEY_REFERER, "ads");
					i.putExtra(Constants.STORE_KEY, getArguments().getString(Constants.STORE_KEY));
					i.putExtra(Constants.AUTO_INSTALL, bannerList.get(key).getAutoInstall());
					startActivity(i);
				}
				
			} else {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse(bannerList.get(key).getUrl()));
				startActivity(intent);
			}
		}
	}
	
	public void onEventMainThread(AllBannerSuccessEvent event){
		bannerList = event.getBannerList();
		if(bannerList.containsKey("header1")){
			displayBanner("header1", bannerList, R.id.big_ad1);
			aquery.id(R.id.big_ad1).clicked(this);
		}
		if(bannerList.containsKey("header11")){
			displayBanner("header11", bannerList, R.id.medium_ad1);
			aquery.id(R.id.medium_ad1).clicked(this);
		}
		if(bannerList.containsKey("header12")){
			displayBanner("header12", bannerList, R.id.medium_ad2);
			aquery.id(R.id.medium_ad2).clicked(this);
		}
		if(bannerList.containsKey("header13")){
			displayBanner("header13", bannerList, R.id.medium_ad3);
			aquery.id(R.id.medium_ad3).clicked(this);
		}
		if(bannerList.containsKey("header14")){
			displayBanner("header14", bannerList, R.id.medium_ad4);
			aquery.id(R.id.medium_ad4).clicked(this);
		}
		if(bannerList.containsKey("header21")){
			displayBanner("header21", bannerList, R.id.big_ad2);
			aquery.id(R.id.big_ad2).clicked(this);
		}
		if(bannerList.containsKey("header31")){
			displayBanner("header31", bannerList, R.id.medium_ad5);
			aquery.id(R.id.medium_ad5).clicked(this);
		}
		if(bannerList.containsKey("header32")){
			displayBanner("header32", bannerList, R.id.medium_ad6);
			aquery.id(R.id.medium_ad6).clicked(this);
		}
		if(bannerList.containsKey("header33")){
			displayBanner("header33", bannerList, R.id.medium_ad7);
			aquery.id(R.id.medium_ad7).clicked(this);
		}
		if(bannerList.containsKey("header34")){
			displayBanner("header34", bannerList, R.id.medium_ad8);
			aquery.id(R.id.medium_ad8).clicked(this);
		}
		if(bannerList.containsKey("header41")){
			displayBanner("header41", bannerList, R.id.big_ad3);
			aquery.id(R.id.big_ad3).clicked(this);
		}
		if(bannerList.containsKey("header51")){
			displayBanner("header51", bannerList, R.id.medium_ad9);
			aquery.id(R.id.medium_ad9).clicked(this);
		}
		if(bannerList.containsKey("header52")){
			displayBanner("header52", bannerList, R.id.medium_ad10);
			aquery.id(R.id.medium_ad10).clicked(this);
		}
		if(bannerList.containsKey("header53")){
			displayBanner("header53", bannerList, R.id.medium_ad11);
			aquery.id(R.id.medium_ad11).clicked(this);
		}
		if(bannerList.containsKey("header54")){
			displayBanner("header54", bannerList, R.id.medium_ad12);
			aquery.id(R.id.medium_ad12).clicked(this);
		}
		if(bannerList.containsKey("footer1")){
			displayBanner("footer1", bannerList, R.id.big_ad4);
			aquery.id(R.id.big_ad4).clicked(this);
		}
		showUpdateMessage();
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.big_ad1:
			onClickBanner("header1");
			break;
		case R.id.medium_ad1:
			onClickBanner("header11");
			break;
		case R.id.medium_ad2:
			onClickBanner("header12");
			break;
		case R.id.medium_ad3:
			onClickBanner("header13");
			break;
		case R.id.medium_ad4:
			onClickBanner("header14");
			break;
		case R.id.big_ad2:
			onClickBanner("header21");
			break;
		case R.id.medium_ad5:
			onClickBanner("header31");
			break;
		case R.id.medium_ad6:
			onClickBanner("header32");
			break;
		case R.id.medium_ad7:
			onClickBanner("header33");
			break;
		case R.id.medium_ad8:
			onClickBanner("header34");
			break;
		case R.id.big_ad3:
			onClickBanner("header41");
			break;
		case R.id.medium_ad9:
			onClickBanner("header51");
			break;
		case R.id.medium_ad10:
			onClickBanner("header52");
			break;
		case R.id.medium_ad11:
			onClickBanner("header53");
			break;
		case R.id.medium_ad12:
			onClickBanner("header54");
			break;
		case R.id.big_ad4:
			onClickBanner("footer1");
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void displayBanner(String key, Map<String, BannerItem> bannerList, int imageViewId){
		
		aquery.id(imageViewId).image(bannerList.get(key).getImages(), false, true, 0, 0, null, AQuery.FADE_IN_NETWORK);
	}
	
	private void showUpdateMessage(){
		Date date = new Date();
		String savedDate = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getString(KEY_DATE, "");
		int shown = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getInt(KEY_IS_SHOWN, 0);
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
		String todayStr = sdf.format(date);
		try {
			Date today = sdf.parse(todayStr);
			Date saved = sdf.parse(savedDate);
			if(today.compareTo(saved) >= 0 && shown == 0){
				//check update content
				if(getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getString(SettingsActivity.KEY_NOTIFY_UPDATE, "true").equalsIgnoreCase("true")){
					String accessToken = Utils.getStaticAccessToken(getActivity());
					try {
						bgTask.checkUpdateContent(accessToken, "apps", 0, 100, Constants.ANDROID_STORE, Utils.getPackageNameList(mContext), true);
					} catch (NameNotFoundException e) {
						e.printStackTrace();
					}
				}
				getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putInt(KEY_IS_SHOWN, 1).commit();
				getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(KEY_DATE, todayStr).commit();
			}
		} catch (Exception e){
			
		}
	}
	
	public void onEventMainThread(HasUpdateContentEvent event){
		if(event.isShowNotification()){
			List<AppStoreVnApplicationInfo> list = event.getList();
			NotificationHelper notification = new NotificationHelper(mContext);
			List<String> itemName = new ArrayList<String>();
			for(AppStoreVnApplicationInfo app : list){
				itemName.add(app.getName());
			}
			Intent intent = new Intent(mContext, AppManageActivity.class);
			intent.putExtra(Constants.STORE_KEY, "apps");
			PendingIntent pi = PendingIntent.getActivity(mContext, APP_ACTIVITY_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.createContentUpdateNotification(Constants.APP_UPDATE_NOTIFICATION_ID, mContext.getResources().getString(R.string.update_title), list.size(), TextUtils.join(", ", itemName), pi);
		}
	}

}
